package com.fowo.api.costAccounting.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fowo.api.costAccounting.entity.MonthlyCostReport;
import com.fowo.api.costAccounting.mapper.CommonCostingMapper;
import com.fowo.api.costAccounting.model.stock.StockOutMonthlyVo;
import com.fowo.api.costAccounting.service.CostAccountingService;
import com.fowo.api.costAccounting.mapper.MonthlyCostReportMapper;
import com.fowo.api.costAccounting.utils.DateUtils;
import com.fowo.api.costAccounting.model.bd.BdAccperiodmonthVo;
import com.fowo.api.costAccounting.model.monthly.MonthlyCostReportItemVo;
import com.fowo.api.costAccounting.model.monthly.MonthlyVo;
import com.fowo.api.costAccounting.model.stock.StockInMonthlyVo;
import com.fowo.api.inventory.entity.InventoryMonthly;
import com.fowo.api.inventory.mapper.InventoryMonthlyMapper;
import com.fowo.api.inventory.model.InventoryMonthlyItemVo;
import liquibase.pro.packaged.E;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class CostAccountingServiceImpl  implements CostAccountingService {
//    @Autowired
//    private AccountingConfigService accountingConfigService;


    @Autowired
    private MonthlyCostReportMapper monthlyCostReportMapper;
    @Autowired
    private CommonCostingMapper commonCostingMapper;

    @Autowired
    private InventoryMonthlyMapper inventoryMonthlyMapper;

    /**   月报表
     *  结转
     *  1、根据会计期间的月度日期范围，重算库存表、成本表 比较其中差异
     *  2、根据会计月份获取下一会计期间，将库存表、成本表结转到下一会计月度期初  //查询所有出入库根据分组 添加
     *  3、更新所有出入库表的状态为已结账（不允许修改）
     * @throws Exception
     */
    @Override
    public void carryForward() throws Exception {

        //  List<BdAccperiodmonthVo> bdAccperiodmonthVoList=bdAccperiodmonthMapper.getByIsCurrentAccperiod();
        List<BdAccperiodmonthVo> bdAccperiodmonthVoList=commonCostingMapper.getByStatus();
        if(bdAccperiodmonthVoList.size()==0||bdAccperiodmonthVoList.size()>1){
            throw new Exception("会计月份查出多条或没有符合得数据");
        }
        if(bdAccperiodmonthVoList.get(0).getBeginDate()==null||bdAccperiodmonthVoList.get(0).getEndDate()==null){
            throw new Exception("会计月份开始时间结束日期未设置");
        }
        int count = monthlyCostReportMapper.getByPeriodIdCount(bdAccperiodmonthVoList.get(0).getId(),null);
        if (count > 0) {
            throw new Exception("本月已经结转");
        }
        //获取当月 处理获取上个月配置的日期查询出
        String ym= bdAccperiodmonthVoList.get(0).getAccperiodMonth();
        if(StringUtils.isBlank(ym)){
            throw new Exception("会计月份未配置");
        }
        //上个月的
        List<BdAccperiodmonthVo> lastbdAccperiodmonthVoList = commonCostingMapper.getByAccperiodMonth(DateUtils.getLastMonth(ym));
        if (lastbdAccperiodmonthVoList.size() != 1) {
            throw new Exception("上个月会计月份查出多条或没有符合得数据");
        }
        if (lastbdAccperiodmonthVoList.get(0).getBeginDate() == null || lastbdAccperiodmonthVoList.get(0).getEndDate() == null) {
            throw new Exception("上个会计月份开始时间结束日期未设置");
        }
        List<MonthlyCostReportItemVo> monthlyCostReportItemVos= monthlyCostReportMapper.getByPeriodId("2",lastbdAccperiodmonthVoList.get(0).getId());
        //处理上月数据
        //本月入库数据可能上月得没有 查询入库得数据 比较上月没有得物料添加
        //this.carryForwardList(monthlyCostReportItemVos,bdAccperiodmonthVoList.get(0),lastbdAccperiodmonthVoList.get(0),"1");
        try {
            ThreadPoolExecutor executor=new ThreadPoolExecutor(10,10,1, TimeUnit.SECONDS,new LinkedBlockingQueue());
            int listSize = monthlyCostReportItemVos.size();
            int fetchSize = 1000; //900条执行一IC  in orcale最大查询1000
            for (int i = 0; i < monthlyCostReportItemVos.size(); i += fetchSize) {
                try {
                    if (i + fetchSize > listSize) {        //作用为toIndex最后没有100条数据则剩余几条newList中就装几条
                        fetchSize = listSize - i;
                    }
                    List<MonthlyCostReportItemVo> list = monthlyCostReportItemVos.subList(i, i + fetchSize);
                    if (CollectionUtils.isEmpty(list)) {
                        continue;
                        // throw new AbstractException("500", "无相关订单数据,请刷新重试");
                    }
                    Date startDate= new Date();
                    executor.submit(()-> {this.carryForwardThr(list,bdAccperiodmonthVoList.get(0),lastbdAccperiodmonthVoList.get(0),"2");});
                    Date endDate1= new Date();
                    System.out.println("线程执行"+list.get(0).getItemId()+"-"+list.get(list.size()-1).getItemId());
                } catch (Exception e) {
                    log.info("处理失败 ", e);
                }
            }
            executor.shutdown();
            while (true) {
                if (executor.isTerminated()) {
                    break;
                }
//                Thread.sleep(200);
            }

        }catch (Exception e ){
            e.printStackTrace();
        }
        carryForwardList(bdAccperiodmonthVoList.get(0),lastbdAccperiodmonthVoList.get(0),"2");
        // 数量有 金额 查询对应物料查询价格 更新到成本月报表
//        monthlyCostReportMapper.insertCopy(DateUtils.getTimesBegin(bdAccperiodmonthVoList.get(0).getBeginDate()),DateUtils.getTimesEnd(bdAccperiodmonthVoList.get(0).getEndDate()));
    }

    /**
     * 查询上月入库数据比较成本表物料 没有的 添加到成本月报
     * @param bdAccperiodmonthVo 当月会计周期
     * @param lastbdAccperiodmonthVoList 上月会计周期
     * @param type
     */
    private void carryForwardList(BdAccperiodmonthVo bdAccperiodmonthVo,BdAccperiodmonthVo lastbdAccperiodmonthVoList, String type) {
        try{

            List<StockInMonthlyVo> stockInMonthlyVoList=commonCostingMapper.getNotReportStockIn(lastbdAccperiodmonthVoList.getId(),lastbdAccperiodmonthVoList.getBeginDate(),lastbdAccperiodmonthVoList.getEndDate());
//        List<StockInMonthlyVo> listadd =
//                stockInMonthlyVoList.stream().filter(item -> !list.stream().map(up -> up.getItemId()).collect(
//                        Collectors.toList()).contains(item.getItemId())).collect(Collectors.toList());
            for (StockInMonthlyVo stockInMonthlyVo : stockInMonthlyVoList) {
                Integer count=monthlyCostReportMapper.getByPeriodIdCount(lastbdAccperiodmonthVoList.getId(),stockInMonthlyVo.getItemId());
                if(count!=0){
                    continue;
                }
                StockOutMonthlyVo stockOutMonthlyVo=commonCostingMapper.getByMonthlyCostReportByOut(null,stockInMonthlyVo.getItemId(),null,stockInMonthlyVo.getStockId(),type,lastbdAccperiodmonthVoList.getBeginDate(),lastbdAccperiodmonthVoList.getEndDate());
                //计算出 期初金额放入
                Integer beginQty=stockInMonthlyVo.getQty()-Optional.ofNullable(stockOutMonthlyVo).map(out -> out.getQty()).orElse(0);
                BigDecimal beginAmount=stockInMonthlyVo.getAmount().subtract(Optional.ofNullable(stockOutMonthlyVo).map(out -> out.getAmount()).orElse(new BigDecimal(0.00)));
                MonthlyCostReport monthlyCostReport=new MonthlyCostReport();
                monthlyCostReport.setBeginAmount(beginAmount);
                monthlyCostReport.setBeginQty(beginQty);
                monthlyCostReport.setItemId(stockInMonthlyVo.getItemId());
                monthlyCostReport.setPeriodId(bdAccperiodmonthVo.getId());
                monthlyCostReport.setStockId(stockInMonthlyVo.getStockId());
                monthlyCostReport.setCreateTime(new Date());
                monthlyCostReportMapper.insert(monthlyCostReport);
            }
        }catch (Exception e){
            log.error("成本月报结转异常-新增",e);
        }

    }

    /**
     * 获取上个月成本月报 获取上个月出入库 计算期末数据 直接添加到下个月度期初数据
     * @param list 上个月成本期初
     * @param bdAccperiodmonthVo 当月会计周期
     * @param lastbdAccperiodmonthVoList 上月会计周期
     * @param type 类型
     */
    private void carryForwardThr(List<MonthlyCostReportItemVo> list, BdAccperiodmonthVo bdAccperiodmonthVo,BdAccperiodmonthVo lastbdAccperiodmonthVoList, String type){
        try{
            for (MonthlyCostReportItemVo monthlyCostReportItemVo : list) {
                Integer beginQty=monthlyCostReportItemVo.getBeginQty();
                BigDecimal beginAmount=monthlyCostReportItemVo.getBeginAmount();
                //获取上个月入库数据
                StockInMonthlyVo stockInMonthlyVo=commonCostingMapper.getByMonthlyCostReport(null,monthlyCostReportItemVo.getItemId(),null,monthlyCostReportItemVo.getStockId(),type,lastbdAccperiodmonthVoList.getBeginDate(),lastbdAccperiodmonthVoList.getEndDate());
                beginQty += Optional.ofNullable(stockInMonthlyVo).map(in -> in.getQty()).orElse(0);
                BigDecimal inAmount = Optional.ofNullable(stockInMonthlyVo).map(in -> in.getAmount()).orElse(new BigDecimal(0.00));
                //获取上月出库数据
                StockOutMonthlyVo stockOutMonthlyVo=commonCostingMapper.getByMonthlyCostReportByOut(null,monthlyCostReportItemVo.getItemId(),null,monthlyCostReportItemVo.getStockId(),type,lastbdAccperiodmonthVoList.getBeginDate(),lastbdAccperiodmonthVoList.getEndDate());
                beginQty -= Optional.ofNullable(stockOutMonthlyVo).map(out -> out.getQty()).orElse(0);
                BigDecimal outAmount = Optional.ofNullable(stockOutMonthlyVo).map(out -> out.getAmount()).orElse(new BigDecimal(0.00));
                //计算期初金额数量添加到成本月报表
//            Integer beginQty=monthlyCostReportItemVo.getBeginQty()+stockInMonthlyVo.getQty()-stockOutMonthlyVo.getQty();
//            BigDecimal beginAmount=monthlyCostReportItemVo.getBeginAmount().add(stockInMonthlyVo.getAmount()).subtract(stockOutMonthlyVo.getAmount());

                MonthlyCostReport monthlyCostReport=new MonthlyCostReport();
                monthlyCostReport.setBeginAmount(beginAmount.add(inAmount).subtract(outAmount));
                monthlyCostReport.setBeginQty(beginQty);
                monthlyCostReport.setItemId(monthlyCostReportItemVo.getItemId());
                monthlyCostReport.setPeriodId(bdAccperiodmonthVo.getId());
                monthlyCostReport.setStockId(monthlyCostReportItemVo.getStockId());
                monthlyCostReport.setCreateTime(new Date());
                monthlyCostReportMapper.insert(monthlyCostReport);
            }
        }catch (Exception e){
            log.error("成本月报结转异常",e);
        }

    }

    @Override
    public void InventoryMonthlyCarryForward() throws Exception{
        List<BdAccperiodmonthVo> bdAccperiodmonthVoList=commonCostingMapper.getByStatus();
        if(bdAccperiodmonthVoList.size()==0||bdAccperiodmonthVoList.size()>1){
            throw new Exception("会计月份查出多条或没有符合得数据");
        }
        if(bdAccperiodmonthVoList.get(0).getBeginDate()==null||bdAccperiodmonthVoList.get(0).getEndDate()==null){
            throw new Exception("会计月份开始时间结束日期未设置");
        }

        Long count = inventoryMonthlyMapper.selectCount(Wrappers.lambdaQuery(InventoryMonthly.class).eq(InventoryMonthly::getPeriodId,bdAccperiodmonthVoList.get(0).getId()));
        if (count > 0) {
            throw new Exception("本月已经结转");
        }
        //获取当月 处理获取上个月配置的日期查询出
        String ym= bdAccperiodmonthVoList.get(0).getAccperiodMonth();
        if(StringUtils.isBlank(ym)){
            throw new Exception("会计月份未配置");
        }
        //上个月的
        List<BdAccperiodmonthVo> lastbdAccperiodmonthVoList = commonCostingMapper.getByAccperiodMonth(DateUtils.getLastMonth(ym));
        if (lastbdAccperiodmonthVoList.size() != 1) {
            throw new Exception("上个月会计月份查出多条或没有符合得数据");
        }
        if (lastbdAccperiodmonthVoList.get(0).getBeginDate() == null || lastbdAccperiodmonthVoList.get(0).getEndDate() == null) {
            throw new Exception("上个会计月份开始时间结束日期未设置");
        }
        List<InventoryMonthlyItemVo> inventoryMonthlyItemVos= inventoryMonthlyMapper.getByPeriodId(lastbdAccperiodmonthVoList.get(0).getId());
        //处理上月数据
        //本月入库数据可能上月得没有 查询入库得数据 比较上月没有得物料添加
        //this.carryForwardList(monthlyCostReportItemVos,bdAccperiodmonthVoList.get(0),lastbdAccperiodmonthVoList.get(0),"1");
        try {
            ThreadPoolExecutor executor=new ThreadPoolExecutor(10,10,1, TimeUnit.SECONDS,new LinkedBlockingQueue());
            int listSize = inventoryMonthlyItemVos.size();
            int fetchSize = 1000; //900条执行一IC  in orcale最大查询1000
            for (int i = 0; i < inventoryMonthlyItemVos.size(); i += fetchSize) {
                try {
                    if (i + fetchSize > listSize) {        //作用为toIndex最后没有100条数据则剩余几条newList中就装几条
                        fetchSize = listSize - i;
                    }
                    List<InventoryMonthlyItemVo> list = inventoryMonthlyItemVos.subList(i, i + fetchSize);
                    if (CollectionUtils.isEmpty(list)) {
                        continue;
                        // throw new AbstractException("500", "无相关订单数据,请刷新重试");
                    }
                    Date startDate= new Date();
                    executor.submit(()-> {this.InventoryMonthlyCarryForwardThr(list,bdAccperiodmonthVoList.get(0),lastbdAccperiodmonthVoList.get(0),"2");});
                    Date endDate1= new Date();
                    System.out.println("线程执行"+list.get(0).getItemId()+"-"+list.get(list.size()-1).getItemId());
                } catch (Exception e) {
                    log.info("处理失败 ", e);
                }
            }
            executor.shutdown();
            while (true) {
                if (executor.isTerminated()) {
                    break;
                }
//                Thread.sleep(200);
            }

        }catch (Exception e ){
            e.printStackTrace();
        }
        InventoryMonthlyCarryForwardList(bdAccperiodmonthVoList.get(0),lastbdAccperiodmonthVoList.get(0),"2");
    }

    /**
     * 查询上月入库数据比较成本表物料 没有的 添加到成本月报
     * @param bdAccperiodmonthVo 当月会计周期
     * @param lastbdAccperiodmonthVoList 上月会计周期
     * @param type
     */
    private void InventoryMonthlyCarryForwardList(BdAccperiodmonthVo bdAccperiodmonthVo,BdAccperiodmonthVo lastbdAccperiodmonthVoList, String type) {
        try{

            List<StockInMonthlyVo> stockInMonthlyVoList=commonCostingMapper.getNotInventoryMonthlyStockIn(lastbdAccperiodmonthVoList.getId(),lastbdAccperiodmonthVoList.getBeginDate(),lastbdAccperiodmonthVoList.getEndDate());
            for (StockInMonthlyVo stockInMonthlyVo : stockInMonthlyVoList) {
                StockOutMonthlyVo stockOutMonthlyVo=commonCostingMapper.getByMonthlyCostReportByOut(null,stockInMonthlyVo.getItemId(),null,stockInMonthlyVo.getStockId(),type,lastbdAccperiodmonthVoList.getBeginDate(),lastbdAccperiodmonthVoList.getEndDate());
                //计算出 期初金额放入
                Integer beginQty=stockInMonthlyVo.getQty()-Optional.ofNullable(stockOutMonthlyVo).map(out -> out.getQty()).orElse(0);
                BigDecimal beginAmount=stockInMonthlyVo.getAmount().subtract(Optional.ofNullable(stockOutMonthlyVo).map(out -> out.getAmount()).orElse(new BigDecimal(0.00)));

                InventoryMonthly inventoryMonthly=new InventoryMonthly();
                inventoryMonthly.setBeginAmount(beginAmount);
                inventoryMonthly.setBeginQty(new BigDecimal(beginQty));
                inventoryMonthly.setItemId(stockInMonthlyVo.getItemId());
                inventoryMonthly.setPeriodId(bdAccperiodmonthVo.getId());
                inventoryMonthly.setStockId(stockInMonthlyVo.getStockId());
                inventoryMonthly.setCreateTime(new Date());
                inventoryMonthlyMapper.insert(inventoryMonthly);
            }
        }catch (Exception e){
            log.error("库存月报结转异常-新增",e);
        }

    }

    /**
     * 获取上个月成本月报 获取上个月出入库 计算期末数据 直接添加到下个月度期初数据
     * @param list 上个月成本期初
     * @param bdAccperiodmonthVo 当月会计周期
     * @param lastbdAccperiodmonthVoList 上月会计周期
     * @param type 类型
     */
    private void InventoryMonthlyCarryForwardThr(List<InventoryMonthlyItemVo> list, BdAccperiodmonthVo bdAccperiodmonthVo,BdAccperiodmonthVo lastbdAccperiodmonthVoList, String type){
        try{
            for (InventoryMonthlyItemVo inventoryMonthlyItemVo : list) {
                BigDecimal beginQty=inventoryMonthlyItemVo.getBeginQty();
                BigDecimal beginAmount=inventoryMonthlyItemVo.getBeginAmount();
                //获取上个月入库数据
                StockInMonthlyVo stockInMonthlyVo=commonCostingMapper.getByMonthlyCostReport(null,inventoryMonthlyItemVo.getItemId().longValue(),null,inventoryMonthlyItemVo.getStockId(),type,lastbdAccperiodmonthVoList.getBeginDate(),lastbdAccperiodmonthVoList.getEndDate());

                BigDecimal inQty = Optional.ofNullable(stockInMonthlyVo).map(in -> new BigDecimal(in.getQty())).orElse(new BigDecimal(0.00));
                BigDecimal inAmount = Optional.ofNullable(stockInMonthlyVo).map(in -> in.getAmount()).orElse(new BigDecimal(0.00));
                //获取上月出库数据
                StockOutMonthlyVo stockOutMonthlyVo=commonCostingMapper.getByMonthlyCostReportByOut(null,inventoryMonthlyItemVo.getItemId().longValue(),null,inventoryMonthlyItemVo.getStockId(),type,lastbdAccperiodmonthVoList.getBeginDate(),lastbdAccperiodmonthVoList.getEndDate());
                BigDecimal outQty = Optional.ofNullable(stockInMonthlyVo).map(out -> new BigDecimal(out.getQty())).orElse(new BigDecimal(0.00));
                BigDecimal outAmount = Optional.ofNullable(stockOutMonthlyVo).map(out -> out.getAmount()).orElse(new BigDecimal(0.00));

                InventoryMonthly inventoryMonthly = new InventoryMonthly();
                inventoryMonthly.setBeginAmount(beginAmount.add(inAmount).subtract(outAmount));
                inventoryMonthly.setBeginQty(beginQty.add(inQty).subtract(outQty));
                inventoryMonthly.setItemId(inventoryMonthlyItemVo.getItemId());
                inventoryMonthly.setPeriodId(bdAccperiodmonthVo.getId());
                inventoryMonthly.setStockId(inventoryMonthlyItemVo.getStockId());
                inventoryMonthly.setCreateTime(new Date());
                inventoryMonthlyMapper.insert(inventoryMonthly);
            }
        }catch (Exception e){
            log.error("库存月报结转异常",e);
        }

    }

    /**
     * 成本核算
     * 1 根据维度(1 - 组织+物料; 2 - 组织+仓库+物料; 3 - 组织+店铺+物料; )
     * 2 查询 基础表（bd_accperiodmonth(会计月份) 当前会计期）多条or没有异常
     * 3 根据维度+会计月份设置得开始时间-结束时间  查询 成本月报（monthly_cost_report）
     * 4 查询3得数据 +会计月份设置得开始时间-结束时间  查询出入库单（stock_in）
     *   月报表得取得本期入库 +入库 成本金额，期初金额+入库金额/期初数量+入库数
     *   量=当期加权平均价。更新 销售出库单（sales_outbound） 出库单（stock_out）
     *   成本金额字段
     * 成本核算
     * 1 取得期初库存 +成本金额
     * 2 取得本期入库 +入库 成本金额
     * 3期初金额+入库金额/期初数量+入库数量=当期加权平均价
     * 4 更新当期出库成本金额=出库数量*当期加权平均价 ；更新当期库存成本金额=库存数量*当期加权平均价
     * 更新成本月报
     * @param type 配置的类型 (1 - 组织+物料; 2 - 组织+仓库+物料; 3 - 组织+店铺+物料; )
     * @throws Exception
     */

    @Override
    public void updateMonthlyCostReport(String type) throws Exception {
        System.out.println("开始时间--"+new Date());
        // 配置得查询
//        AccountingConfigVo accountingConfigVo= accountingConfigService.getVoById(id);
//        if(accountingConfigVo==null){
//            throw new Exception("暂未找到配置");
//        }
        //获取会计月份bd_accperiodmonth  是否当前会计期 获取对应的数据 如果多条没有直接报错
        //是否需要会计的内码查询过滤？？
        //组织+物料
        //List<BdAccperiodmonthVo> bdAccperiodmonthVoList=bdAccperiodmonthMapper.getByIsCurrentAccperiod();
        List<BdAccperiodmonthVo> bdAccperiodmonthVoList= commonCostingMapper.getByStatus();
        if(bdAccperiodmonthVoList.size()==0||bdAccperiodmonthVoList.size()>1){
            throw new Exception("会计月份查出多条或没有符合得数据");
        }
        if(bdAccperiodmonthVoList.get(0).getBeginDate()==null||bdAccperiodmonthVoList.get(0).getEndDate()==null){
            throw new Exception("会计月份开始时间结束日期未设置");
        }
        if("1".equals(type)){
            typeOneThread(type,bdAccperiodmonthVoList.get(0));
        }else if("2".equals(type)){
            //2 - 组织+仓库+物料
            typeTwoThread(type,bdAccperiodmonthVoList.get(0));
        }else if("3".equals(type)){
            //2 - 组织+店铺+物料
            typeThreeThread(type,bdAccperiodmonthVoList.get(0));
        }else {
            //  - 组织+店铺+物料+fnsku  店铺可能为空，fnsku可能为空 暂未设置
            throw  new Exception("类型不对");
        }
    }


    public void typeOneThread(String type,BdAccperiodmonthVo bdAccperiodmonthVo) throws Exception{
        //List<MonthlyCostReportItemVo> monthlyCostReportItemVos= monthlyCostReportMapper.getByNowData(type,bdAccperiodmonthVo.getBeginDate(),bdAccperiodmonthVo.getEndDate());
        List<MonthlyCostReportItemVo> monthlyCostReportItemVos= monthlyCostReportMapper.getByPeriodId(type,bdAccperiodmonthVo.getId());
        try {
            ThreadPoolExecutor executor=new ThreadPoolExecutor(10,10,1, TimeUnit.SECONDS,new LinkedBlockingQueue());
            int listSize = monthlyCostReportItemVos.size();
            int fetchSize = 1000; //900条执行一IC  in orcale最大查询1000
            for (int i = 0; i < monthlyCostReportItemVos.size(); i += fetchSize) {
                try {
                    if (i + fetchSize > listSize) {        //作用为toIndex最后没有100条数据则剩余几条newList中就装几条
                        fetchSize = listSize - i;
                    }
                    List<MonthlyCostReportItemVo> list = monthlyCostReportItemVos.subList(i, i + fetchSize);
                    if (CollectionUtils.isEmpty(list)) {
                        continue;
                        // throw new AbstractException("500", "无相关订单数据,请刷新重试");
                    }
                    Date startDate= new Date();
                   executor.submit(()-> {this.typeOneThre(list,bdAccperiodmonthVo.getBeginDate(),bdAccperiodmonthVo.getEndDate(),type);});
                    Date endDate1= new Date();
                    System.out.println("线程执行"+list.get(0).getItemId()+"-"+list.get(list.size()-1).getItemId());
                } catch (Exception e) {
                    log.info("处理失败 ", e);
                }
            }
            executor.shutdown();
            while (true) {
                if (executor.isTerminated()) {
                    break;
                }
                Thread.sleep(200);
            }

        }catch (Exception e ){
            e.printStackTrace();
        }

    }
    @Transactional(rollbackFor = Exception.class)
    public void typeOneThre(List<MonthlyCostReportItemVo> monthlyCostReportItemVos,Date beginDate,Date endDate,String type) {
        Date startDate= new Date();
        System.out.println("执行中"+monthlyCostReportItemVos.get(0).getItemId()+"-"+monthlyCostReportItemVos.get(monthlyCostReportItemVos.size()-1).getItemId());
        List<MonthlyVo> monthlyVoList=new ArrayList<>();
        for (MonthlyCostReportItemVo monthlyCostReportItemVo : monthlyCostReportItemVos) {
            StockInMonthlyVo stockInMonthlyVo=commonCostingMapper.getByMonthlyCostReport(monthlyCostReportItemVo.getOrgId(),monthlyCostReportItemVo.getItemId(),null,null,type,beginDate,endDate);

            BigDecimal sumAmount=new BigDecimal(0);
            Integer sumCount=0;
            if(stockInMonthlyVo==null){
                sumAmount= monthlyCostReportItemVo.getBeginAmount();
                sumCount= monthlyCostReportItemVo.getBeginQty();
            }else {
                //如果期初金额 0 直接直接入库金额÷入库数量
                if(monthlyCostReportItemVo.getBeginAmount().compareTo(BigDecimal.ZERO)==0){
                    sumAmount= stockInMonthlyVo.getAmount();
                    sumCount=  stockInMonthlyVo.getQty();
                }else {
//                    //如果入库金额是0 重新获取价格计算 临时表获取
//                    if(stockInMonthlyVo.getAmount().compareTo(BigDecimal.ZERO)==0){
//                        BigDecimal  price= commonCostingMapper.getSKUPrice(monthlyCostReportItemVo.getItemId());
//                        stockInMonthlyVo.setAmount(price.multiply(new BigDecimal(stockInMonthlyVo.getQty())));
//                    }
                    sumAmount= monthlyCostReportItemVo.getBeginAmount().add(stockInMonthlyVo.getAmount());
                    sumCount=  stockInMonthlyVo.getQty()+monthlyCostReportItemVo.getBeginQty();
                }
            }
            // 更新出库单  销售出库单 根据过滤得条件 筛选
            MonthlyVo monthlyVo=new MonthlyVo();
            monthlyVo.setOrgId(monthlyCostReportItemVo.getOrgId());
            monthlyVo.setItemId(monthlyCostReportItemVo.getItemId());
            monthlyVo.setBeginDate(DateUtils.getTimesBegin(beginDate));
            monthlyVo.setEndDate(DateUtils.getTimesEnd(endDate));
            if(sumCount==0){
                continue;
            }
            //计算 当期加权平均价
            BigDecimal weightedAverage=sumAmount.divide( BigDecimal.valueOf(sumCount),2,BigDecimal.ROUND_HALF_UP);
            monthlyVo.setAmount(weightedAverage);
            monthlyVoList.add(monthlyVo);
//            commonCostingMapper.updateStockOutByType(monthlyVo);
//            commonCostingMapper.updateSalesOutboundByType(monthlyVo);
        }
        Date endDate1= new Date();
        System.out.println("执行结束"+monthlyCostReportItemVos.get(0).getItemId()+"--"+monthlyCostReportItemVos.get(monthlyCostReportItemVos.size()-1).getItemId()+"-用时"+(endDate1.getTime()-startDate.getTime()));
        commonCostingMapper.updateStockOutByTypeBatch(monthlyVoList);
        commonCostingMapper.updateSalesOutboundByTypeBatch(monthlyVoList);
         endDate1= new Date();
        System.out.println("执行结束修改"+monthlyCostReportItemVos.get(0).getItemId()+"--"+monthlyCostReportItemVos.get(monthlyCostReportItemVos.size()-1).getItemId()+"-用时"+(endDate1.getTime()-startDate.getTime())+"endDate1"+endDate1);
    }
    public void typeTwoThread(String type,BdAccperiodmonthVo bdAccperiodmonthVo) throws Exception{
        //List<MonthlyCostReportItemVo> monthlyCostReportItemVos= monthlyCostReportMapper.getByNowData(type,bdAccperiodmonthVo.getBeginDate(),bdAccperiodmonthVo.getEndDate());
        List<MonthlyCostReportItemVo> monthlyCostReportItemVos= monthlyCostReportMapper.getByPeriodId(type,bdAccperiodmonthVo.getId());
        try {
            ThreadPoolExecutor executor=new ThreadPoolExecutor(10,10,1, TimeUnit.SECONDS,new LinkedBlockingQueue());
            int listSize = monthlyCostReportItemVos.size();
            int fetchSize = 1000; //900条执行一IC  in orcale最大查询1000
            for (int i = 0; i < monthlyCostReportItemVos.size(); i += fetchSize) {
                try {
                    if (i + fetchSize > listSize) {        //作用为toIndex最后没有100条数据则剩余几条newList中就装几条
                        fetchSize = listSize - i;
                    }
                    List<MonthlyCostReportItemVo> list = monthlyCostReportItemVos.subList(i, i + fetchSize);
                    if (CollectionUtils.isEmpty(list)) {
                        continue;
                        // throw new AbstractException("500", "无相关订单数据,请刷新重试");
                    }
                    Date startDate= new Date();
                    executor.submit(()-> {this.typeTwoThre(list,bdAccperiodmonthVo.getBeginDate(),bdAccperiodmonthVo.getEndDate(),type);});
                    Date endDate1= new Date();
                    System.out.println("线程执行"+list.get(0).getItemId()+"-"+list.get(list.size()-1).getItemId());
                } catch (Exception e) {
                    log.info("处理失败 ", e);
                }
            }
            executor.shutdown();
            while (true) {
                if (executor.isTerminated()) {
                    break;
                }
                Thread.sleep(200);
            }

        }catch (Exception e ){
            e.printStackTrace();
        }
    }
    @Transactional(rollbackFor = Exception.class)
    public void typeTwoThre(List<MonthlyCostReportItemVo> monthlyCostReportItemVos,Date beginDate,Date endDate,String type) {
        Date startDate= new Date();
        System.out.println("执行中"+monthlyCostReportItemVos.get(0).getItemId()+"-"+monthlyCostReportItemVos.get(monthlyCostReportItemVos.size()-1).getItemId());
        List<MonthlyVo> monthlyVoList=new ArrayList<>();
        for (MonthlyCostReportItemVo monthlyCostReportItemVo : monthlyCostReportItemVos) {
            StockInMonthlyVo stockInMonthlyVo=commonCostingMapper.getByMonthlyCostReport(monthlyCostReportItemVo.getOrgId(),monthlyCostReportItemVo.getItemId(),null,monthlyCostReportItemVo.getStockId(),type,beginDate,endDate);

            BigDecimal sumAmount=new BigDecimal(0);
            Integer sumCount=0;
            if(stockInMonthlyVo==null){
                sumAmount= monthlyCostReportItemVo.getBeginAmount();
                sumCount= monthlyCostReportItemVo.getBeginQty();
            }else {
                //如果期初金额 0 直接直接入库金额÷入库数量
                if(monthlyCostReportItemVo.getBeginAmount().compareTo(BigDecimal.ZERO)==0){
                    sumAmount= stockInMonthlyVo.getAmount();
                    sumCount=  stockInMonthlyVo.getQty();
                }else {
                    sumAmount= monthlyCostReportItemVo.getBeginAmount().add(stockInMonthlyVo.getAmount());
                    sumCount=  stockInMonthlyVo.getQty()+monthlyCostReportItemVo.getBeginQty();
                }
            }
            // 更新出库单  销售出库单 根据过滤得条件 筛选
            MonthlyVo monthlyVo=new MonthlyVo();
            monthlyVo.setOrgId(monthlyCostReportItemVo.getOrgId());
            monthlyVo.setItemId(monthlyCostReportItemVo.getItemId());
            monthlyVo.setStockId(monthlyCostReportItemVo.getStockId());
            monthlyVo.setBeginDate(DateUtils.getTimesBegin(beginDate));
            monthlyVo.setEndDate(DateUtils.getTimesEnd(endDate));
            if(sumCount==0){
                // 直接修改单价放到 成本金额上 danjia
//                stockOutMapper.updateByTypeZero(monthlyVo);
//                salesOutboundMapper.updateByTypeZero(monthlyVo);
                continue;
            }
            //计算 当期加权平均价
            BigDecimal weightedAverage=sumAmount.divide( BigDecimal.valueOf(sumCount),2,BigDecimal.ROUND_HALF_UP);
            // 更新出库单  销售出库单 根据过滤得条件 筛选
            monthlyVo.setAmount(weightedAverage);
            monthlyVoList.add(monthlyVo);
//            commonCostingMapper.updateStockOutByType(monthlyVo);
//            commonCostingMapper.updateSalesOutboundByType(monthlyVo);
        }
        Date endDate1= new Date();
        System.out.println("执行结束"+monthlyCostReportItemVos.get(0).getItemId()+"--"+monthlyCostReportItemVos.get(monthlyCostReportItemVos.size()-1).getItemId()+"-用时"+(endDate1.getTime()-startDate.getTime()));
        commonCostingMapper.updateStockOutByTypeBatch(monthlyVoList);
        commonCostingMapper.updateSalesOutboundByTypeBatch(monthlyVoList);
        endDate1= new Date();
        System.out.println("执行结束修改"+monthlyCostReportItemVos.get(0).getItemId()+"--"+monthlyCostReportItemVos.get(monthlyCostReportItemVos.size()-1).getItemId()+"-用时"+(endDate1.getTime()-startDate.getTime()));
    }
    public void typeThreeThread(String type,BdAccperiodmonthVo bdAccperiodmonthVo) throws Exception{
        //List<MonthlyCostReportItemVo> monthlyCostReportItemVos= monthlyCostReportMapper.getByNowData(type,bdAccperiodmonthVo.getBeginDate(),bdAccperiodmonthVo.getEndDate());
        List<MonthlyCostReportItemVo> monthlyCostReportItemVos= monthlyCostReportMapper.getByPeriodId(type,bdAccperiodmonthVo.getId());
        try {
            ThreadPoolExecutor executor=new ThreadPoolExecutor(10,10,1, TimeUnit.SECONDS,new LinkedBlockingQueue());
            int listSize = monthlyCostReportItemVos.size();
            int fetchSize = 1000; //900条执行一IC  in orcale最大查询1000
            for (int i = 0; i < monthlyCostReportItemVos.size(); i += fetchSize) {
                try {
                    if (i + fetchSize > listSize) {        //作用为toIndex最后没有100条数据则剩余几条newList中就装几条
                        fetchSize = listSize - i;
                    }
                    List<MonthlyCostReportItemVo> list = monthlyCostReportItemVos.subList(i, i + fetchSize);
                    if (CollectionUtils.isEmpty(list)) {
                        continue;
                        // throw new AbstractException("500", "无相关订单数据,请刷新重试");
                    }
                    Date startDate= new Date();
                    executor.submit(()-> {this.typeThreeThre(list,bdAccperiodmonthVo.getBeginDate(),bdAccperiodmonthVo.getEndDate(),type);});
                    Date endDate1= new Date();
                    System.out.println("线程执行"+list.get(0).getItemId()+"-"+list.get(list.size()-1).getItemId());
                } catch (Exception e) {
                    log.info("处理失败 ", e);
                }
            }
            executor.shutdown();
            while (true) {
                if (executor.isTerminated()) {
                    break;
                }
                Thread.sleep(200);
            }

        }catch (Exception e ){
            e.printStackTrace();
        }
    }
    @Transactional(rollbackFor = Exception.class)
    public void typeThreeThre(List<MonthlyCostReportItemVo> monthlyCostReportItemVos,Date beginDate,Date endDate,String type) {
        Date startDate= new Date();
        System.out.println("执行中"+monthlyCostReportItemVos.get(0).getItemId()+"-"+monthlyCostReportItemVos.get(monthlyCostReportItemVos.size()-1).getItemId());
        List<MonthlyVo> monthlyVoList=new ArrayList<>();
        for (MonthlyCostReportItemVo monthlyCostReportItemVo : monthlyCostReportItemVos) {
            StockInMonthlyVo stockInMonthlyVo=commonCostingMapper.getByMonthlyCostReport(monthlyCostReportItemVo.getOrgId(),monthlyCostReportItemVo.getItemId(),monthlyCostReportItemVo.getShopId(),null,type,beginDate,endDate);

            BigDecimal sumAmount=new BigDecimal(0);
            Integer sumCount=0;
            if(stockInMonthlyVo==null){
                sumAmount= monthlyCostReportItemVo.getBeginAmount();
                sumCount= monthlyCostReportItemVo.getBeginQty();
            }else {
                //如果期初金额 0 直接直接入库金额÷入库数量
                if(monthlyCostReportItemVo.getBeginAmount().compareTo(BigDecimal.ZERO)==0){
                    sumAmount= stockInMonthlyVo.getAmount();
                    sumCount=  stockInMonthlyVo.getQty();
                }else {
                    sumAmount= monthlyCostReportItemVo.getBeginAmount().add(stockInMonthlyVo.getAmount());
                    sumCount=  stockInMonthlyVo.getQty()+monthlyCostReportItemVo.getBeginQty();
                }
            }
            if(sumCount==0){
                // 直接修改单价放到 成本金额上 danjia
//                stockOutMapper.updateByTypeZero(monthlyVo);
//                salesOutboundMapper.updateByTypeZero(monthlyVo);
                continue;
            }
            //计算 当期加权平均价
            BigDecimal weightedAverage=sumAmount.divide( BigDecimal.valueOf(sumCount),2,BigDecimal.ROUND_HALF_UP);
            MonthlyVo monthlyVo=new MonthlyVo();
            monthlyVo.setOrgId(monthlyCostReportItemVo.getOrgId());
            monthlyVo.setItemId(monthlyCostReportItemVo.getItemId());
            monthlyVo.setAmount(weightedAverage);
            monthlyVo.setShopId(monthlyCostReportItemVo.getShopId());
            monthlyVo.setBeginDate(DateUtils.getTimesBegin(beginDate));
            monthlyVo.setEndDate(DateUtils.getTimesEnd(endDate));
            // 更新出库单  销售出库单 根据过滤得条件 筛选
            monthlyVoList.add(monthlyVo);
//            commonCostingMapper.updateStockOutByType(monthlyVo);
//            commonCostingMapper.updateSalesOutboundByType(monthlyVo);
        }
        Date endDate1= new Date();
        System.out.println("执行结束"+monthlyCostReportItemVos.get(0).getItemId()+"--"+monthlyCostReportItemVos.get(monthlyCostReportItemVos.size()-1).getItemId()+"-用时"+(endDate1.getTime()-startDate.getTime()));
        commonCostingMapper.updateStockOutByTypeBatch(monthlyVoList);
        commonCostingMapper.updateSalesOutboundByTypeBatch(monthlyVoList);
        endDate1= new Date();
        System.out.println("执行结束修改"+monthlyCostReportItemVos.get(0).getItemId()+"--"+monthlyCostReportItemVos.get(monthlyCostReportItemVos.size()-1).getItemId()+"-用时"+(endDate1.getTime()-startDate.getTime()));
    }
    @Transactional(rollbackFor = Exception.class)
    public void typeOne(String type,BdAccperiodmonthVo bdAccperiodmonthVo) throws Exception{
        List<MonthlyCostReportItemVo> monthlyCostReportItemVos= monthlyCostReportMapper.getByNowData(type,bdAccperiodmonthVo.getBeginDate(),bdAccperiodmonthVo.getEndDate());
        int row=0;
        for (MonthlyCostReportItemVo monthlyCostReportItemVo : monthlyCostReportItemVos) {
            row++;
            System.out.println("执行第"+row);
            StockInMonthlyVo stockInMonthlyVo=commonCostingMapper.getByMonthlyCostReport(monthlyCostReportItemVo.getOrgId(),monthlyCostReportItemVo.getItemId(),null,null,type,bdAccperiodmonthVo.getBeginDate(),bdAccperiodmonthVo.getEndDate());

            BigDecimal sumAmount=new BigDecimal(0);
            Integer sumCount=0;
            if(stockInMonthlyVo==null){
                sumAmount= monthlyCostReportItemVo.getBeginAmount();
                sumCount= monthlyCostReportItemVo.getBeginQty();
            }else {
                //如果期初金额 0 直接直接入库金额÷入库数量
                if(monthlyCostReportItemVo.getBeginAmount().compareTo(BigDecimal.ZERO)==0){
                    sumAmount= stockInMonthlyVo.getAmount();
                    sumCount=  stockInMonthlyVo.getQty();
                }else {
                    sumAmount= monthlyCostReportItemVo.getBeginAmount().add(stockInMonthlyVo.getAmount());
                    sumCount=  stockInMonthlyVo.getQty()+monthlyCostReportItemVo.getBeginQty();
                }
            }
            // 更新出库单  销售出库单 根据过滤得条件 筛选
            MonthlyVo monthlyVo=new MonthlyVo();
            monthlyVo.setOrgId(monthlyCostReportItemVo.getOrgId());
            monthlyVo.setItemId(monthlyCostReportItemVo.getItemId());
            monthlyVo.setBeginDate(DateUtils.getTimesBegin(bdAccperiodmonthVo.getBeginDate()));
            monthlyVo.setEndDate(DateUtils.getTimesEnd(bdAccperiodmonthVo.getEndDate()));
            if(sumCount==0){
                // 直接修改单价放到 成本金额上 danjia
//                stockOutMapper.updateByTypeZero(monthlyVo);
//                salesOutboundMapper.updateByTypeZero(monthlyVo);
                continue;
            }
            //计算 当期加权平均价
            BigDecimal weightedAverage=sumAmount.divide( BigDecimal.valueOf(sumCount),2,BigDecimal.ROUND_HALF_UP);
            monthlyVo.setAmount(weightedAverage);
            commonCostingMapper.updateStockOutByType(monthlyVo);
            commonCostingMapper.updateSalesOutboundByType(monthlyVo);
//            StockOutMonthlyVo stockOutnMonthlyVo=stockOutMapper.getByMonthlyCostReport(monthlyCostReportItemVo.getOrgId(),monthlyCostReportItemVo.getItemId(),null,null,type);
//            MonthlyCostReport monthlyCostReport=new MonthlyCostReport();
//            monthlyCostReport.setOrgId(monthlyCostReportItemVo.getOrgId());
//            monthlyCostReport.setItemId(monthlyCostReportItemVo.getItemId());
//            monthlyCostReport.setStockInQty(stockInMonthlyVo.getQty());
//            monthlyCostReport.setStockInAmount(weightedAverage.multiply(BigDecimal.valueOf(stockInMonthlyVo.getQty())));
//            monthlyCostReport.setStockOutQty(stockOutnMonthlyVo.getQty());
//            monthlyCostReport.setStockOutAmount(weightedAverage.multiply(BigDecimal.valueOf(stockOutnMonthlyVo.getQty())));
//            monthlyCostReportMapper.updateByType(monthlyCostReport);

        }
    }
    @Transactional(rollbackFor = Exception.class)
    public void typeTwo(String type,BdAccperiodmonthVo bdAccperiodmonthVo) throws Exception{
        List<MonthlyCostReportItemVo> monthlyCostReportItemVos= monthlyCostReportMapper.getByNowData(type,bdAccperiodmonthVo.getBeginDate(),bdAccperiodmonthVo.getEndDate());
        for (MonthlyCostReportItemVo monthlyCostReportItemVo : monthlyCostReportItemVos) {
            StockInMonthlyVo stockInMonthlyVo=commonCostingMapper.getByMonthlyCostReport(monthlyCostReportItemVo.getOrgId(),monthlyCostReportItemVo.getItemId(),null,monthlyCostReportItemVo.getStockId(),type,bdAccperiodmonthVo.getBeginDate(),bdAccperiodmonthVo.getEndDate());

            BigDecimal sumAmount=new BigDecimal(0);
            Integer sumCount=0;
            if(stockInMonthlyVo==null){
                sumAmount= monthlyCostReportItemVo.getBeginAmount();
                sumCount= monthlyCostReportItemVo.getBeginQty();
            }else {
                //如果期初金额 0 直接直接入库金额÷入库数量
                if(monthlyCostReportItemVo.getBeginAmount().compareTo(BigDecimal.ZERO)==0){
                    sumAmount= stockInMonthlyVo.getAmount();
                    sumCount=  stockInMonthlyVo.getQty();
                }else {
                    sumAmount= monthlyCostReportItemVo.getBeginAmount().add(stockInMonthlyVo.getAmount());
                    sumCount=  stockInMonthlyVo.getQty()+monthlyCostReportItemVo.getBeginQty();
                }
            }
            // 更新出库单  销售出库单 根据过滤得条件 筛选
            MonthlyVo monthlyVo=new MonthlyVo();
            monthlyVo.setOrgId(monthlyCostReportItemVo.getOrgId());
            monthlyVo.setItemId(monthlyCostReportItemVo.getItemId());
            monthlyVo.setStockId(monthlyCostReportItemVo.getStockId());
            monthlyVo.setBeginDate(DateUtils.getTimesBegin(bdAccperiodmonthVo.getBeginDate()));
            monthlyVo.setEndDate(DateUtils.getTimesEnd(bdAccperiodmonthVo.getEndDate()));
            if(sumCount==0){
                // 直接修改单价放到 成本金额上 danjia
//                stockOutMapper.updateByTypeZero(monthlyVo);
//                salesOutboundMapper.updateByTypeZero(monthlyVo);
                continue;
            }
            //计算 当期加权平均价
            BigDecimal weightedAverage=sumAmount.divide( BigDecimal.valueOf(sumCount),2,BigDecimal.ROUND_HALF_UP);
            // 更新出库单  销售出库单 根据过滤得条件 筛选
            monthlyVo.setAmount(weightedAverage);
            commonCostingMapper.updateStockOutByType(monthlyVo);
            commonCostingMapper.updateSalesOutboundByType(monthlyVo);
//            StockOutMonthlyVo stockOutnMonthlyVo=stockOutMapper.getByMonthlyCostReport(monthlyCostReportItemVo.getOrgId(),monthlyCostReportItemVo.getItemId(),null,monthlyCostReportItemVo.getStockId(),type);
//            MonthlyCostReport monthlyCostReport=new MonthlyCostReport();
//            monthlyCostReport.setOrgId(monthlyCostReportItemVo.getOrgId());
//            monthlyCostReport.setItemId(monthlyCostReportItemVo.getItemId());
//            monthlyCostReport.setStockId(monthlyCostReportItemVo.getStockId());
//            monthlyCostReport.setStockInQty(stockInMonthlyVo.getQty());
//            monthlyCostReport.setStockInAmount(weightedAverage.multiply(BigDecimal.valueOf(stockInMonthlyVo.getQty())));
//            monthlyCostReport.setStockOutQty(stockOutnMonthlyVo.getQty());
//            monthlyCostReport.setStockOutAmount(weightedAverage.multiply(BigDecimal.valueOf(stockOutnMonthlyVo.getQty())));
//            monthlyCostReportMapper.updateByType(monthlyCostReport);

        }
    }
    @Transactional(rollbackFor = Exception.class)
    public void typeThree(String type,BdAccperiodmonthVo bdAccperiodmonthVo) throws Exception{
        List<MonthlyCostReportItemVo> monthlyCostReportItemVos= monthlyCostReportMapper.getByNowData(type,bdAccperiodmonthVo.getBeginDate(),bdAccperiodmonthVo.getEndDate());
        for (MonthlyCostReportItemVo monthlyCostReportItemVo : monthlyCostReportItemVos) {
            StockInMonthlyVo stockInMonthlyVo=commonCostingMapper.getByMonthlyCostReport(monthlyCostReportItemVo.getOrgId(),monthlyCostReportItemVo.getItemId(),monthlyCostReportItemVo.getShopId(),null,type,bdAccperiodmonthVo.getBeginDate(),bdAccperiodmonthVo.getEndDate());

            BigDecimal sumAmount=new BigDecimal(0);
            Integer sumCount=0;
            if(stockInMonthlyVo==null){
                sumAmount= monthlyCostReportItemVo.getBeginAmount();
                sumCount= monthlyCostReportItemVo.getBeginQty();
            }else {
                //如果期初金额 0 直接直接入库金额÷入库数量
                if(monthlyCostReportItemVo.getBeginAmount().compareTo(BigDecimal.ZERO)==0){
                    sumAmount= stockInMonthlyVo.getAmount();
                    sumCount=  stockInMonthlyVo.getQty();
                }else {
                    sumAmount= monthlyCostReportItemVo.getBeginAmount().add(stockInMonthlyVo.getAmount());
                    sumCount=  stockInMonthlyVo.getQty()+monthlyCostReportItemVo.getBeginQty();
                }
            }
            if(sumCount==0){
                // 直接修改单价放到 成本金额上 danjia
//                stockOutMapper.updateByTypeZero(monthlyVo);
//                salesOutboundMapper.updateByTypeZero(monthlyVo);
                continue;
            }
            //计算 当期加权平均价
            BigDecimal weightedAverage=sumAmount.divide( BigDecimal.valueOf(sumCount),2,BigDecimal.ROUND_HALF_UP);
            MonthlyVo monthlyVo=new MonthlyVo();
            monthlyVo.setOrgId(monthlyCostReportItemVo.getOrgId());
            monthlyVo.setItemId(monthlyCostReportItemVo.getItemId());
            monthlyVo.setAmount(weightedAverage);
            monthlyVo.setShopId(monthlyCostReportItemVo.getShopId());
            monthlyVo.setBeginDate(DateUtils.getTimesBegin(bdAccperiodmonthVo.getBeginDate()));
            monthlyVo.setEndDate(DateUtils.getTimesEnd(bdAccperiodmonthVo.getEndDate()));
            commonCostingMapper.updateStockOutByType(monthlyVo);
            commonCostingMapper.updateSalesOutboundByType(monthlyVo);
//            StockOutMonthlyVo stockOutnMonthlyVo=stockOutMapper.getByMonthlyCostReport(monthlyCostReportItemVo.getOrgId(),monthlyCostReportItemVo.getItemId(),monthlyCostReportItemVo.getShopId(),null,type);
//            MonthlyCostReport monthlyCostReport=new MonthlyCostReport();
//            monthlyCostReport.setOrgId(monthlyCostReportItemVo.getOrgId());
//            monthlyCostReport.setItemId(monthlyCostReportItemVo.getItemId());
//            monthlyCostReport.setShopId(monthlyCostReportItemVo.getShopId());
//            monthlyCostReport.setStockInQty(stockInMonthlyVo.getQty());
//            monthlyCostReport.setStockInAmount(weightedAverage.multiply(BigDecimal.valueOf(stockInMonthlyVo.getQty())));
//            monthlyCostReport.setStockOutQty(stockOutnMonthlyVo.getQty());
//            monthlyCostReport.setStockOutAmount(weightedAverage.multiply(BigDecimal.valueOf(stockOutnMonthlyVo.getQty())));
//            monthlyCostReportMapper.updateByType(monthlyCostReport);

        }
    }

}
